<template>
  <p-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭">
    <p-spin tip="Loading..." :spinning="false">
      <p-tree
        checkable
        :treeData="treeData"
        :loadData="onLoadData"
        :checkStrictly="true"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand"
        :autoExpandParent="autoExpandParent"
        :expandedKeys="expandedKeys"
        :replaceFields="replaceFields"
        :checkedKeys="checkedKeys">
        <template slot="title" slot-scope="{title}">
          <span v-if="title.indexOf(searchValue) > -1">
            {{title.substr(0, title.indexOf(searchValue))}}
            <span style="color: #f50">{{searchValue}}</span>
            {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
          </span>
          <span v-else>{{title}}</span>
        </template>
      </p-tree>
    </p-spin>
  </p-modal>
</template>

<script>
  import { queryConpanyTreeList,queryDepartTreeList } from '@/api/api'
  export default {
    name: 'JSelectDepartModal',
    props:['modalWidth','multi','rootOpened','departId','type'],
    data(){
      return {
        visible:false,
        confirmLoading:false,
        treeData:[],
        autoExpandParent:true,
        expandedKeys:[],
        dataList:[],
        checkedKeys:[],
        checkedRows:[],
        searchValue:"",
        replaceFields:{
          children:'children', title:'name', key:'code'
        }
      }
    },
    created(){
      this.loadDepart();
    },
    watch:{
      visible: {
        handler() {
          if (this.departId) {
            this.checkedKeys = this.departId.split(",");
          } else {
            this.checkedKeys = [];
          }
        }
      }
    },
    methods:{
       onLoadData(treeNode) {

        return new Promise(resolve => {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
          queryConpanyTreeList({'code':treeNode.dataRef.code}).then((res) => {
            if (res.success) {
              let children = []
              res.data.forEach((item,index)=>{
                item['isLeaf'] = item.leaf
                children.push(item)
              })
              treeNode.dataRef.children = children
              this.treeData = [...this.treeData];
               resolve();
            }
          })  
        });
      },
      show(){
        this.visible=true
        this.checkedRows=[]
        this.checkedKeys=[]
      },
      loadDepart(){
        queryConpanyTreeList({'code':'company'}).then(res=>{
          if(res.success){
            let arr = []
            let children = []
            if(this.type == 'factory'){
              res.data.forEach((item,index)=>{
                item['isLeaf'] = item.leaf
                item['disabled'] = true
                arr.push(item)
              })
            }else{
              res.data.forEach((item,index)=>{
                item['isLeaf'] = true
                arr.push(item)
              })
            }
            this.treeData = arr
          }
        })
      },
      
     
     
      onCheck (checkedKeys,info) {
       
        if(!this.multi){
          let arr = checkedKeys.checked.filter(item => this.checkedKeys.indexOf(item) < 0)
          this.checkedKeys = [...arr]
          this.checkedRows = (this.checkedKeys.length === 0) ? [] : [info.node.dataRef]
        }else{
          this.checkedKeys = checkedKeys.checked
          this.checkedRows = this.getCheckedRows(this.checkedKeys)
        }
      },
      onSelect(selectedKeys,info) {
        let keys = []
        
        keys.push(selectedKeys[0])
        if(!this.checkedKeys || this.checkedKeys.length===0 || !this.multi){
          this.checkedKeys = [...keys]
         
        }else{
          let currKey = info.node.dataRef.key
          if(this.checkedKeys.indexOf(currKey)>=0){
            this.checkedKeys = this.checkedKeys.filter(item=> item !==currKey)
          }else{
            this.checkedKeys.push(...keys)
          }
        }
        this.checkedRows=[info.node.dataRef]
      },
      onExpand (expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      handleSubmit(){
        if(!this.checkedKeys || this.checkedKeys.length==0){
          this.$emit("ok",'')
        }else{
          this.$emit("ok",this.checkedRows,this.checkedKeys.join(","))
        }
        this.handleClear()
      },
      handleCancel(){
        this.handleClear()
      },
      handleClear(){
        this.visible=false
        this.checkedKeys=[]
      },
      getParentKey(currKey,treeData){
        let parentKey
        for (let i = 0; i < treeData.length; i++) {
          const node = treeData[i]
          if (node.children) {
            if (node.children.some(item => item.key === currKey)) {
              parentKey = node.key
            } else if (this.getParentKey(currKey, node.children)) {
              parentKey = this.getParentKey(currKey, node.children)
            }
          }
        }
        return parentKey
      },
      onSearch(value){
        const expandedKeys = this.dataList.map((item) => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key,this.treeData)
          }
          return null
        }).filter((item, i, self) => item && self.indexOf(item) === i)

        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })
      },
      // 根据 checkedKeys 获取 rows
      getCheckedRows(checkedKeys) {
        const forChildren = (list, key) => {
          for (let item of list) {
            if (item.id === key) {
              return item
            }
            if (item.children instanceof Array) {
              let value = forChildren(item.children, key)
              if (value != null) {
                return value
              }
            }
          }
          return null
        }

        let rows = []
        for (let key of checkedKeys) {
          let row = forChildren(this.treeData, key)
          if (row != null) {
            rows.push(row)
          }
        }
        return rows
      }
    }
  }

</script>

<style scoped>

</style>